/**
 * Created by xinhuang on 15/6/9.
 */
(function (angular) {
  'use strict';

  angular.module('controllers.customActivity.realtime', [
    'services.customActivity.realtime'
  ])
    .controller('activityListController', activityListController)
    .controller('realtimeFormController', realtimeFormController);

  activityListController.$inject = ['$scope', '$state', '$mdDialog', 'dialogFormService', 'activityList', 'activityManager', 'realtimeServer'];
  function activityListController($scope, $state, $mdDialog, dialogFormService, activityList, activityManager, realtimeServer) {
    $scope.activityList = activityList;
    //获取活动列表
    $scope.activityList.getList(function () {
      $scope.coreLoading = true;
    });
    //页面跳转
    $scope.goToDisplayPage = function (activity, ev) {
      //通过服务器检查活动状态
      realtimeServer.activityStateCheck(activity.activityId)
        .success(function (res) {
          // 1004: 活动进行中  1005: 活动已结束
          if (res.state === '1004' || res.state === '1005') {
            $state.go('sas.realTimeDisplay', {activityId: activity.activityId});
            return;
          }
          dialogFormService.alert(res.message, ev);
        });
    };

    //修改或新增活动
    $scope.modifyActivity = function (ev, activityId) {

      //重置activityManager
      activityManager.reset();

      //新增活动
      if (is.undefined(activityId)) {
        dialogFormService.newDialog(ev, 'edit')
          .then(
          function () {     //成功则重新刷新活动列表
            $scope.coreLoading = false;
            $scope.activityList.getList(function () {
              $scope.coreLoading = true;
            });
          },
          function () {     //否则清除表单
            activityManager.reset();
          });
      } else {
        //修改活动
        ev.stopPropagation();
        realtimeServer.activityStateCheck(activityId)
          .success(function (res) {
            //活动已结束时不能修改活动
            if (res.state === '1005' || res.state === '1006') {
              dialogFormService.alert(res.message);
              //获取活动列表
              $scope.activityList.getList(function () {
                $scope.coreLoading = true;
              });
              return;
            }
            //更新当前活动信息
            activityManager.activityInfo.activityId = activityId;
            activityManager.activityInfo.activityState = res.state;
            dialogFormService.newDialog(ev, activityId, 'edit')
              .then(
              //同新增活动
              function () {
                $scope.coreLoading = false;
                $scope.activityList.getList(function () {
                  $scope.coreLoading = true;
                });
              },
              function () {
                activityManager.reset();
              });
          });
      }


    };

    //删除活动
    $scope.deleteActivity = function (activityId, ev) {
      ev.stopPropagation();
      dialogFormService.confirm('删除后将无法恢复,同时对应活动总结页面也会删除,您确定要继续删除吗?')
        .then(function () {
          activityList.deleteActivity(activityId);
        });
    };

    $scope.$on('$destroy', function(){
      $mdDialog.cancel();
    });
  }

  realtimeFormController.$inject = ['$scope', '$mdDialog', '$state', 'checkboxManager', 'activityManager', 'provinceAutoComplete', 'formState', 'dialogFormService'];
  function realtimeFormController($scope, $mdDialog, $state, checkboxManager, activityManager, provinceAutoComplete, formState, dialogFormService) {
    var startTime = new Date(), endTime;
    startTime.setDate(startTime.getDate() + 1);
    startTime.setHours(0);
    startTime.setMinutes(0);
    startTime.setSeconds(0);
    startTime.setMilliseconds(0);
    endTime = angular.copy(startTime);
    endTime.setDate(startTime.getDate() + 3);

    $scope.editState = is.undefined(activityManager.activityInfo.activityId) ? '新增' : '修改';
    $scope.activityState = activityManager.activityInfo.activityState;
    $scope.autoDisabled = false;
    $scope.selectedProvince = [];
    $scope.activityManager = activityManager;
    $scope.checkboxManager = checkboxManager;
    $scope.provinceAutoComplete = provinceAutoComplete;


    $scope.autoComplete = {
      hide: 'all',
      hideChanged: function (str) {
        return str === 'all';
      }
    };

    if(formState === 'preview'){
      activityManager.resume();

      if (activityManager.configure.provinceCode.length < 31) {
        $scope.autoComplete.hide = 'some';
        $scope.selectedProvince = provinceAutoComplete.getSelectedProvince(activityManager.configure.provinceCode);
      }
      $scope.coreLoading = true;
    } else {
      provinceAutoComplete.getProvince();

      activityManager.getConfigModules(function () {
        if (is.not.undefined(activityManager.activityInfo.activityId)) {
          activityManager.getSavedConfig(activityManager.activityInfo.activityId, function () {
            if (activityManager.configure.provinceCode.length < 31) {
              $scope.autoComplete.hide = 'some';
              $scope.selectedProvince = provinceAutoComplete.getSelectedProvince(activityManager.configure.provinceCode);
            }
            $scope.coreLoading = true;
          });
        } else {
          $scope.activityManager.startTime = startTime;
          $scope.activityManager.endTime = angular.copy(endTime);
          $scope.coreLoading = true;
        }
      });
    }
    function removeNotObject(arr){
      var proObj = [];
      angular.forEach(arr,function(pro){
        if(typeof pro === 'object'){
          proObj.push(pro);
        }
      });
      return proObj;
    }
    $scope.$watch('selectedProvince',function(n,o){
      $scope.selectedProvince = removeNotObject($scope.selectedProvince);
    },true);
    $scope.saveActivity = function () {
      var proCode;
      if ($scope.autoComplete.hide === 'all') {
        proCode = $scope.provinceAutoComplete.provinces.map(function (province) {
          return province.provinceCode;
        });
      } else {
        proCode = $scope.selectedProvince.map(function (province) {
          return province.provinceCode;
        });
      }
      $scope.activityManager.configure.provinceCode = proCode;
      console.log(activityManager.activityInfo.activityId);
      $scope.activityManager.saveActivity(activityManager.activityInfo.activityId, function (err) {
        if (angular.isDefined(err)) {
          alert(err);
        } else {
          $mdDialog.hide();
        }
      });
    };


    $scope.preview = function () {
      var proCode;

      activityManager.setConfigure();

      if ($scope.autoComplete.hide === 'all') {
        proCode = $scope.provinceAutoComplete.provinces.map(function (province) {
          return province.provinceCode;
        });
      } else {
        proCode = $scope.selectedProvince.map(function (province) {
          return province.provinceCode;
        });
      }
      $scope.activityManager.configure.provinceCode = proCode;

      if(activityManager.configure.selectedModules.length === 0){
        return dialogFormService.alert('至少选择一个模块');
      }
      $state.go('sas.activityEdit');
      $mdDialog.hide();
    };

    $scope.cancel = function () {
      dialogFormService.confirm('您确定要关闭窗口？关闭后数据将不保存')
        .then(function(){
          $mdDialog.cancel();
        });
    };

    $scope.$on('$destroy', function(){
      provinceAutoComplete.searchText = null;
    });
  }
})(angular);
